# --coding: utf-8 --
from openpyxl import load_workbook
import numpy as np
from xiaowupkg import *


def getMsgTimes():
    timelist = [170000, 180000, 190000, 200000, 210000]
    timenow = int(time.strftime('%H%M%S', time.localtime(time.time())))
    if timenow >= 170000:
        for index, item in enumerate(timelist):
            # print(index, item)
            if timenow >= item and timenow <= item + 10000:
                return index
    return -1
    # print(timenow)

def readxlsx(path, sheet = '当天提醒'):
    global clients
    # 读取Excel文件
    workbook = load_workbook(path)
    worksheet = workbook[sheet]
    
    # 打印数据
    for cols in worksheet.iter_cols(values_only=True):
        coltext = []
        for col in cols:
            if type(col) is not datetime.time and col is not None:
                coltext.append(col)
        clients.append(coltext)
    # print(clients)

def moyuFunction(function):
    #    获取群聊关键字
    if function == 1:
        readxlsx('file.xlsx', '当天提醒')
    elif function == 2:
        readxlsx('file.xlsx', '明日提醒')
    global clients
    # print(clients)
    global contact
    #今日提醒
    if function == 1:
        info = '注意时间哦，等会要上课了~'
        timenow = int(time.strftime('%H%M%S', time.localtime(time.time())))
        if timenow <= 223000:
            index = getMsgTimes()
            # index = 0
            #输出提醒信息
            send_error = []
            wx = AutoWxGui(contact)
            wx.open_wechat()
            count = 1
            if index != -1:
                for client in clients[index]:
                    try:
                        print(client,":",info)
                        wx.search_chat_with_pic(client, 'image.png')
                        wx.send_msg(info + str(count))
                        count += 1
                    except Exception as e:
                        # 处理未知类型的异常
                        wx.msg_alarm("发送消息失败", e)
                        send_error.append(client)
                wx.msg_alarm("当前提醒任务已完成：" + str(index))
            else:
                wx.msg_alarm("当前时间段无提醒："+str(index))
    elif function == 2:
        #明日提醒
        info = '明天有课哦～'
        #输出提醒信息
        send_error = []
        wx = AutoWxGui(contact)
        wx.open_wechat()
        print(len(clients[0]))
        print(len(clients[1]))
        count = 1
        for client,allmsg in zip(clients[0], clients[1]):
            try:
                retmsg = info + " " + allmsg + " " + str(count)
                print(client,":",retmsg)
                wx.search_chat_with_pic(client, 'image.png')
                wx.send_msg(retmsg)
                count+=1
            except Exception as e:
                # 处理未知类型的异常
                wx.msg_alarm("发送消息失败", e)
                send_error.append(client)
        wx.msg_alarm("明日提醒任务已完成")

def button_clicked():
    global contact
    print("Button clicked!")
    print(window.contact.text())
    window.showwin.setText(window.contact.text())
    if window.contact.text() != '':
        print('程序已启动,紧急联系人为:', window.contact.text())
        window.showwin.setText(f'程序已启动\n你的紧急联系人已设置为:{window.contact.text()}')
        contact = window.contact.text()
        thread.start_new_thread(moyuFunction, (), {"function": 1})
        
    else:
        print('程序已启动,紧急联系人为: 文件传输助手')
        window.showwin.setText('程序已启动\n你的紧急联系人已设置为: 文件传输助手')
        contact = '文件传输助手'
        thread.start_new_thread(moyuFunction, (), {"function": 1})

def button_clicked_2():
    global contact
    print("Button clicked!")
    print(window.contact.text())
    window.showwin.setText(window.contact.text())
    print(type(window.contact.text()))
    print("...",str(window.contact.text()),"...")
    if window.contact.text() != '':
        print('程序已启动,紧急联系人为:', window.contact.text())
        window.showwin.setText(f'程序已启动\n你的紧急联系人已设置为:{window.contact.text()}')
        contact = window.contact.text()
        thread.start_new_thread(moyuFunction, (), {"function": 2})
    else:
        print('程序已启动,紧急联系人为:     ')
        window.showwin.setText('程序已启动\n你的紧急联系人已设置为: 文件传输助手')
        contact = '文件传输助手'
        thread.start_new_thread(moyuFunction, (), {"function": 2})

if __name__ == '__main__':
    contact = ''
    clients = []
    window = MyQtApp('show.ui')
    window.startbut.clicked.connect(button_clicked)
    window.startbut_2.clicked.connect(button_clicked_2)
    window.stopbut.clicked.connect(window.close)
    window.app.exec_()
    sys.exit()
    # gui = AutoWxGui()
    # gui.open_wechat()





    